package net.esj.basic.plugins.freemarker;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;

import net.esj.basic.utils.ApplicationBeanContext;

import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

/**
 * 将struts的freemarkerManager配置放置在spring容器中维护
 * @author Administrator
 *
 */
//@Component("springConfigToFreemarkerManager")
//@Scope("prototype")
//FIXME 该成代码配置而非注解
public class SpringConfigToFreemarkerManager extends FreemarkerManager {
	
	private static final String SPRING_FREEMARKER_BEAN = "freemarkerConfig";

	private Configuration userConfiguration;
	
	@Override  
    protected Configuration createConfiguration(ServletContext servletContext)   
            throws TemplateException {   
		FreeMarkerConfigurer fmconfig = (FreeMarkerConfigurer) ApplicationBeanContext.getBean(SPRING_FREEMARKER_BEAN);
        try {
        	Configuration configuration =fmconfig.createConfiguration();
        	configuration.setWhitespaceStripping(true);
			return  configuration;
		} catch (IOException e) {
			e.printStackTrace();
		}   
		return super.createConfiguration(servletContext);
    }   

	protected Configuration createUserConfiguration(ServletContext servletContext) throws TemplateException{
		userConfiguration =createConfiguration(servletContext);
		
		String realpath = servletContext.getRealPath("/");
		
		try {
			userConfiguration.setDirectoryForTemplateLoading(new File(realpath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return userConfiguration;
	}

	public Configuration getUserConfiguration(ServletContext servletContext) {
		if(userConfiguration==null){
			try {
				createUserConfiguration(servletContext);
			} catch (TemplateException e) {
				e.printStackTrace();
			}
		}
		return userConfiguration;
	}
}
